var index;

var table;
var form;

$(document).ready(function () {
    $('#page-toolbar-content').show();

    layui.use(['table', 'form'], function () {

        table = layui.table;
        form = layui.form;
        form.render();

        getAllButton(currUrl).done(function (returnData) {
            createButton(returnData);
            initButtonEvent();
            initTable();
        });

    });

});

function initButtonEvent() {

    var $ = layui.$, active = {

        add: function () {
            loadingChildPage('/admin/role/role_add', '新增角色');
        },
        edit: function () {
            var checkStatus = table.checkStatus('role-table-content');
            var data = checkStatus.data;
            if (data.length <= 0) {
                layer.msg("没有选取任何行！");
            }
            else if (data.length > 1) {
                layer.msg("无法批量修改行！");
            }
            else {
                loadingChildPageId('/admin/role/role_edit', "编辑角色", data[0].roleId);
            }
        },
        del: function () {
            var checkStatus = table.checkStatus('role-table-content');
            var data = checkStatus.data;
            if (data.length <= 0) {
                layer.msg("没有选取任何行！");
            }
            else {
                var dataIds = [];
                for (var i = 0; i < data.length; i++) {
                    dataIds[i] = data[i].roleId;
                }

                removeRole(dataIds);
            }
        },
        permission: function () {
            var checkStatus = table.checkStatus('role-table-content');
            var data = checkStatus.data;
            if (data.length <= 0) {
                layer.msg("没有选取任何行！");
            }
            else if (data.length > 1) {
                layer.msg("无法批量修改行！");
            }
            else {
                setRolePermission(data[0].roleId);
            }
        },
        search: function () {

            var roleKey = $('#roleKey');
            var roleName = $('#roleName');
            var roleStatus = $('#roleStatus');

            // 执行重载
            table.reload('role-table-content', {
                page: {
                    curr: 1
                }
                , where: {
                    roleKey: roleKey.val(),
                    roleName: roleName.val(),
                    roleStatus: roleStatus.val()
                }
            });

            $('.layui-table-page').css('text-align', 'right');
            $('.layui-table-page').css('padding-right', '20px');

        }
    };

    $('.menu-btn-group .layui-btn, .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

}

function initTable() {

    table.render({
        elem: '#role-table-content'
        , url: apiHostUrl + '/admin/role/queryRole'
        , headers: {Authorization: token}
        , response: {
            statusName: 'errorCode'
            , statusCode: 0
            , msgName: 'errorMsg'
            , countName: 'totalCount'
            , dataName: 'returnData'
        }
        , cellMinWidth: 50
        , limit: 15
        , limits: [15]
        , cols: [[
            {type: 'checkbox'}
            , {field: 'roleId', width: 80, title: 'ID'}
            , {field: 'roleKey', width: 200, title: 'Key'}
            , {field: 'roleName', width: 200, title: '名称'}
            , {field: 'description', title: '说明'}
            , {field: 'roleSort', width: 100, title: '排序'}
            , {field: 'roleStatusString', width: 70, title: '状态'}
            , {field: 'toolbar', width: 240, title: '操作', align: 'center', toolbar: '#tableToolbar'}
        ]]
        , page: {
            layout: ['prev', 'page', 'next', 'skip', 'limit', 'count']
        }
        , id: 'role-table-content'
    });

    // 监听工具条
    table.on('tool(page-table)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            var dataIds = [];
            dataIds[0] = data.roleId;
            removeRole(dataIds);
        } else if (obj.event === 'edit') {
            loadingChildPageId('/admin/role/role_edit', '编辑角色', data.roleId);
        }
        else if (obj.event === 'permission') {
            setRolePermission(data.roleId);
        }
    });

    $('.layui-table-page').css('text-align', 'right');
    $('.layui-table-page').css('padding-right', '20px');

}

function removeRole(roleIds) {
    layer.confirm("真的要删除该行吗？", function () {
        ajax(
            "/admin/role/delRole", "POST",
            {roleIds: roleIds}
            , true, true, true
        ).done(function () {
            loadingPage("/admin/role/role");
        });
        layer.closeAll();
    });
}

function setRolePermission(roleId) {

    index = layer.open({
        title: "设置角色权限",
        type: 1,
        id: 'layer-page-page',
        shade: 0,
        area: ['330px', '652px'],
        content:
        '<div style="text-align: center;"></div><div id="role-permission-tree" style="padding: 20px;min-height: 500px;max-height: 500px;"></div>' +
        '<hr>' +
        '<div class="layui-form-item" style="text-align: center;margin-bottom: 5px;">' +
        '<button class="layui-btn layui-btn-default"><i class="fa fa-check fa-fw""></i>确认</button>' +
        '<button class="layui-btn layui-btn-danger"><i class="fa fa-reply fa-fw"></i>返回</button></div></div>',
        success: function (alertLayer) {
            var btn_ok = alertLayer.find('.layui-btn-default');
            btn_ok.attr({
                onclick: "javascript:setPermission(" + roleId + ");"
            });
            var btn_cancel = alertLayer.find('.layui-btn-danger');
            btn_cancel.attr({
                onclick: 'layer.closeAll();'
            });
        }
    });

    getAllMenuPermissionTreeData();
}

function setPermission(roleId) {

    var tree = $("#role-permission-tree");
    var nodes = tree.jstree(true).get_checked(false);

    tree.find(".jstree-undetermined").each(function (i, element) {
        nodes.push($(element).closest('.jstree-node').attr("id"));
    });

    var ids = nodes.map(function(data){
        return +data;
    });

    ajax(
        "/admin/role/setPermission", "POST",
        {
            roleId: roleId,
            menuIds: ids
        }
        , true, true, true
    ).done(function () {
        loadingPage("/admin/role/role");
    });
    layer.closeAll();
}

function getAllMenuPermissionTreeData() {

    // 获取所有菜单树
    ajax(
        "/admin/menu/getMenuTree", "POST",
        null, true, true, false
    ).done(function (returnData) {
        createJSTree(returnData);
    });

}

function createJSTree(jsonData) {

    var tree = $('#role-permission-tree');

    tree.jstree({
        plugins: ["state", "checkbox", "types"],
        core: {
            multiple: true,
            themes: {
                responsive: !1,
            },
            data: jsonData
        },
        types: {
            default: {
                icon: "fa fa-folder icon-state-warning icon-lg"
            },
            file: {
                icon: "fa fa-file icon-state-warning icon-lg"
            }
        }
    });

}


